package com.demo.core.service.base.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.demo.core.dao.RoleDao;
import com.demo.core.model.Role;
import com.demo.core.service.base.RoleService;
import com.demo.core.service.exception.RoleAlreadyExistedException;

/**
 * 角色服务实现类
 * @author ryuu.kk
 *
 */
public class RoleServiceImpl implements RoleService {

	/**
	 * 角色数据访问层
	 */
	private RoleDao roleDao;
	
	@Override
	public Long save(Role role) throws RoleAlreadyExistedException {
		Role r = this.find(role.getSiteId(), role.getName());
		if (r != null) {
			throw new RoleAlreadyExistedException(role, "Role already existed.", "role.already.existed");
		}
		return roleDao.insert(role);
	}
	@Override
	public boolean exists(Long id) {
		return roleDao.exists(id);
	}

	@Override
	public void delete(Long roleId) {
		roleDao.delete(roleId);
	}

	@Override
	public void update(Long id, String name, String title, String description) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		Role role = new Role();
		role.setName(name);
		role.setTitle(title);
		role.setDescription(description);
		roleDao.update(role, params);
	}
	
	@Override
	public void changeType(Long roleId, String type) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("id", roleId);
		Role role = new Role();
		role.setType(type);
		roleDao.updateType(role, params);
	}

	@Override
	public void valid(Long roleId, Date expireDay, boolean enabled) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("id", roleId);
		Role role = new Role();
		role.setEnabled(enabled);
		role.setExpireDay(expireDay);
		roleDao.updateStatus(role, params);
	}

	@Override
	public void changePriority(Long roleId, int priority) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("id", roleId);
		Role role = new Role();
		role.setPriority(priority);
		roleDao.updatePriority(role, params);
	}
	
	@Override
	public Role find(Long roleId) {
		return roleDao.select(roleId);
	}

	@Override
	public Role find(Long siteId, String roleName) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("siteId", siteId);
		params.put("name", roleName);
		List<Role> roleList = roleDao.select(params);
		return roleList.size() == 0 ? null : roleList.get(0);
	}

	@Override
	public List<Role> findList(Long siteId) {
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("siteId", siteId);
		return roleDao.select(params);
	}

	@Override
	public List<Role> findAll() {
		return roleDao.select(new HashMap<String, Object>(1));
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
}
